package main

import (
	"fmt"
	uuid "github.com/satori/go.uuid"
	"io"
	"log"
	"net/http"
	"os"
	"path"
	"strings"
)

var staticHandler http.Handler

func main() {
	http.HandleFunc("/", indexHandler)
	port := os.Getenv("PORT")
	if port == "" {
		port = "8080"
		log.Printf("Defaulting to port %s", port)
	}
	dir := path.Dir(os.Args[0])
	staticHandler = http.FileServer(http.Dir(dir))
	http.HandleFunc("/upload_file", uploadFileHandler)

	log.Printf("Listening on port %s", port)
	log.Printf("Open http://localhost:%s in the browser", port)
	log.Fatal(http.ListenAndServe(fmt.Sprintf(":%s", port), nil))
}

func indexHandler(w http.ResponseWriter, r *http.Request) {
	fmt.Println(r.URL.Path)
	if strings.HasPrefix(r.URL.Path, "/res") {
		staticHandler.ServeHTTP(w, r)
		return
	}
	_, err := fmt.Fprint(w, "Hello, World!")
	if err != nil {
		w.WriteHeader(http.StatusInternalServerError)
	}
}

func UUID() string {
	return uuid.NewV1().String()
}

func uploadFileHandler(w http.ResponseWriter, r *http.Request) {
	fmt.Println(r.URL.Path)
	err := r.ParseMultipartForm(1024)
	if err != nil {
		panic(err)
	}
	file, handler, err := r.FormFile("uploadFile")
	if err != nil {
		fmt.Println(err)
		return
	}
	defer file.Close()


	newFile, err := os.OpenFile("./tmp_files/"+handler.Filename + "." + UUID(), os.O_WRONLY|os.O_CREATE, 0666)
	if err != nil {
		panic(err)
	}
	defer newFile.Close()
	_, err = io.Copy(newFile, file)
	if err != nil {
		panic(err)
	}
	_, err = w.Write([]byte("文件上传成功!!!"))
	if err != nil {
		panic(err)
	}
}